import React, {Component,} from 'react';
import {connect,} from 'react-redux';
import {formatDate, formatDateWithDot, handleDateChange,} from "../../../../utils/dateService";
import FootballGameCard from "../../../../shared-components/FootballGameCard/FootballGameCard";
import DateTabs from "../../../../shared-components/DateTabs/DateTabs";
import {GameDataArrayToObject, GameDataObjectFinalized} from "../../../../redux/game";
import NoDataPage from "../NoDataPage/NoDataPage";
import EventFilterList from "../EventFilterList/EventFilterList";
import GameListHandler from "../../../../model/GameList";

class GameSchedule extends Component{
    constructor(props) {
        super(props)
        this.today = formatDate((new Date()))
        this.tabPosition = this.props.tabPosition[2].schedule
        this.state = {
            tabs: [
                {value: this.today, title: '今天', active: this.tabPosition === 0,},
                {value: formatDate(handleDateChange(this.today, 1)), title: formatDateWithDot(handleDateChange(this.today, 1)), active: this.tabPosition === 1,},
                {value: formatDate(handleDateChange(this.today, 2)), title: formatDateWithDot(handleDateChange(this.today, 2)), active: this.tabPosition === 2,},
                {value: formatDate(handleDateChange(this.today, 3)), title: formatDateWithDot(handleDateChange(this.today, 3)), active: this.tabPosition === 3,},
            ],
            currentTabIndex: -1,
            gameListHandler: null,
        }
    }

    componentDidMount() {
        this.getGlobalTapPosition()
        this.fetchList()
        this.setHandler()
    }

    componentDidUpdate(prevProps, prevState, snapshot) {

        const thisIndex = this.state.currentTabIndex
        const prevIndex = prevState.currentTabIndex
        const thisTabs = this.state.tabs
        const prevTabs = prevState.tabs
        if (thisIndex !== prevIndex) {
            this.fetchList()
            this.setHandler()
        }
        const date = this.getDate()
        const thisGames = this.props.game.games[date]
        const prevGames = prevProps.game.games[date]
        if (thisGames !== undefined && thisGames !== prevGames) {
            this.setHandler()
        }
        // const date = this.getDate()
        // const dateGame = this.getDateGames(date)
        // const matches = dateGame ? dateGame.matches : []
        // const prevMatches = prevProps[date] ? prevProps[date].matches : []
        // if (matches.length > 1 && matches.length !== prevMatches.length) {
        //     this.setHandler()
        //     this.fetchList()
        // }
        // if (JSON.stringify(prevState) !== JSON.stringify(this.state)) {
        //     this.setHandler()
        //     this.fetchList()
        // }
    }

    getGlobalTapPosition = () => {
        const tabPosition = this.tabPosition
        this.setState({
            currentTabIndex: tabPosition,
        })
    }

    getDateGames = (date) => {
        const games = this.props.game.games
        const dateGame = games[date]
        // console.log(dateGame)
        return dateGame

    }

    getDate = () => {
        const index = this.state.currentTabIndex
        if (index === -1) return undefined
        const date = this.state.tabs[index].value
        return date
        // const currentTab = this.state.tabs.find(tab => tab.active === true)
        // return currentTab.value
    }

    setHandler = () => {
        const date = this.getDate()
        const dateGame = this.props.game.games[date]
        if (dateGame) {
            const {
                teams,
                events,
                stages,
                matches,
            } = dateGame
            this.setState({
                gameListHandler: new GameListHandler({matches, teams, events, stages,})
            })
        }
    }

    clearHandler = () => {
        this.setState({
            gameListHandler: null,
        })
    }

    fetchList = () => {
        // const currentTab = this.state.tabs.find(tab => tab.active === true)
        // const date = currentTab.value
        // const index = this.state.currentTabIndex
        // if (index === -1) return
        // const date = this.state.tabs[index].value
        const date = this.getDate()
        if (date) {
            const dateMatches = this.props.game.games[date] ? this.props.game.games[date].matches : []
            const doFetchGameListAll = this.props.doFetchGameListAll
            if (date && dateMatches.length === 0) {
                doFetchGameListAll({date,})
            }
        }
    }

    setTabSelected = index => {
        const tabs = this.state.tabs
        let tab
        for (let i = 0; i < tabs.length; i++) {
            if (i === index) {
                tabs[i].active = true
                tab = tabs[i]
            } else {
                tabs[i].active = false
            }
        }
        this.setState({
            tabs: tabs,
        })
    }

    setGlobalTabPosition = (index) => {
        this.props.changeGameTabPosition({
            position: index,
            depth: 2,
            type: 'schedule'
        })
        this.setState({
            currentTabIndex: index,
        })
    }

    emptyFilters = () => {
        this.props.changeEventFilter({
            eventFilters: [],
        })
    }

    onTabSelected = index => {
        this.setTabSelected(index)
        // this.fetchList()
        this.clearHandler()
        this.setGlobalTabPosition(index)
        // this.emptyFilters()
    }


    render() {
        const tabs = this.state.tabs
        const date = this.getDate()
        // const currentTab = tabs.find(tab => tab.active === true)
        // const dateString = currentTab.value
        // const currentTabGames = this.props.game.games[dateString] ? this.props.game.games[dateString] : {}
        // // console.log(c)
        const dateGames = this.getDateGames(date) ? this.getDateGames(date) : {}
        // let listTemplate
        // if (dateGames === undefined) return null
        const {
            events = {},
            stages = {},
            teams = {},
        } = dateGames

        // const confirmMatches = matches.filter(match => match[2] === 1)
        // const delayedMatches = matches.filter(match => match[2] > 8)
        let handler = this.state.gameListHandler
        if (handler === null) {
            return <div
                style={{
                    height: '100%',
                    overflow: 'hidden',
                }}
            >
                <DateTabs
                    tabs={tabs}
                    onTabSelected={this.onTabSelected}
                    today={this.today}
                />
            </div>
        }
        // const confirmMatches = handler.getMatches('')
        const matchesSchedule = handler.getMatches('schedule')
        // const matchesLive = handler.getMatches('live')
        const matchesCancel = handler.getMatches('cancel')

        let matchesToRender
        if (matchesSchedule.length > 0) {
            matchesToRender = [...matchesSchedule]
        } else {
            matchesToRender = [...matchesSchedule, ...matchesCancel]
        }

        const matchesRender = (matches, index) => {
            // if (handler === null)  return null
            let handler = new GameListHandler({matches, teams, events, stages})
            let list = handler.listAll()
            const hot = this.props.hot
            if (hot) {
                const hots = this.props.hots
                list = list.filter(game => {
                    const event = game.event
                    const names = [event.name_zh, event.short_name_zh,]
                    let isHot = false
                    names.map(name => {
                        hots.map(hot => {
                            if (name === hot) {
                                isHot = true
                            }
                        })
                    })
                    return isHot
                })
            }
            let template = list.map((game,i) => <FootballGameCard game={game} key={i}/>)
            return list.length > 0 ? template : <NoDataPage/>
        }



        const gamesTemplate = <EventFilterList
            matches={matchesToRender}
            render={matchesRender}
            // render={(matches) => {
            //     return matches.map(gameArr => {
            //             const gameObjInit = GameDataArrayToObject(gameArr)
            //             const gameObjFinal = GameDataObjectFinalized(gameObjInit, teams, events, stages)
            //             return <FootballGameCard game={gameObjFinal} key={gameObjFinal.matchId}/>
            //         }
            //     )
            // }}
        />

        const list = matchesToRender.length > 0 ? gamesTemplate : <NoDataPage/>

        return <div
            style={{
                height: '100%',
                overflow: 'hidden',
            }}
        >
            <DateTabs
                tabs={tabs}
                onTabSelected={this.onTabSelected}
                today={this.today}
            />
            <div
                style={{
                    height: 'calc(100% - 50px)',
                }}
                className='game-list-ctn'
            >
                {list}
                {/*{list}*/}
            </div>
        </div>
    }
}

const mapState = state => ({
    game: state.game,
    tabPosition: state.game.tabPosition,
})

const mapDispatch = dispatch => ({
    doFetchGameListAll: payload => dispatch.game.doFetchGameListAll(payload),
    changeGameTabPosition: (payload) => dispatch.game.changeGameTabPosition(payload),
    changeEventFilter: (payload) => dispatch.game.changeEventFilter(payload)
})


export default connect(
    mapState,
    mapDispatch
)(GameSchedule)
